package com.yeskery.nut.view.freemarker;

import com.yeskery.nut.view.AbstractViewResolver;
import com.yeskery.nut.view.View;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;

import java.nio.charset.StandardCharsets;
import java.util.Locale;

/**
 * FreeMarker视图解析器
 * @author sprout
 * @version 1.0
 * 2022-07-02 21:55
 */
public class FreeMarkerViewResolver extends AbstractViewResolver {

    /** 默认后缀名 */
    private static final String POSTFIX = "ftl";

    /** FreeMarker配置对象 */
    private final Configuration configuration;

    /**
     * 构建FreeMarker视图解析器
     */
    public FreeMarkerViewResolver() {
        super(POSTFIX);
        configuration =  new Configuration(Configuration.VERSION_2_3_31);
        configuration.setTemplateLoader(new ClassTemplateLoader(this.getClass().getClassLoader(), ""));
        configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
    }

    /**
     * 构建FreeMarker视图解析器
     * @param configuration FreeMarker配置对象
     */
    public FreeMarkerViewResolver(Configuration configuration) {
        super(POSTFIX);
        this.configuration = configuration;
    }

    @Override
    public View createView(String viewName, Locale locale) throws Exception {
        return new FreeMarkerView(configuration, viewName);
    }

    /**
     * 获取配置对象
     * @return 配置对象
     */
    public Configuration getConfiguration() {
        return configuration;
    }
}
